package pers.jsan.litheopen.security.filter.authorize;

import pers.jsan.litheopen.security.exception.LitheAuthenticationException;
import pers.jsan.litheopen.security.filter.AuthenticationFilterChain;
import pers.jsan.litheopen.security.filter.LitheAuthenticationFilter;
import pers.jsan.litheopen.utils.MD5Util;
import pers.jsan.litheopen.utils.RandomCode;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

public class CacheSessionFilter implements LitheAuthenticationFilter {

    private final static String SESSION = "SESSION";

    @Override
    public void doFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse, AuthenticationFilterChain filterChain) throws IOException, ServletException, LitheAuthenticationException {
        Cookie[] cookies = servletRequest.getCookies();
        boolean sessionExist = false;
        if(null != cookies) {
            for (Cookie cookie : cookies) {
                if(SESSION.equals(cookie.getName())) {
                    servletRequest.setAttribute(SESSION, cookie.getValue());
                    sessionExist = true;
                    break;
                }
            }
        }
        //如果SESSION不存在，加SESSION
        if(!sessionExist) {
            servletRequest.setAttribute(SESSION, writeSession(servletResponse));
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private String writeSession(HttpServletResponse response) {
        String value = MD5Util.encryption32(new Timestamp(System.currentTimeMillis()).toString()+ RandomCode.randomString(6));
        Cookie session = new Cookie(SESSION, value);
        session.setPath("/");
        session.setMaxAge(60*60*24*7);
        response.addCookie(session);
        return value;
    }
}
